from PyQt5.QtCore import Qt, QModelIndex, QItemSelection, pyqtSlot

from PyQt5.QtWidgets import QGridLayout,\
                            QMessageBox,\
                            QWidget

from RBK.View.List import List
from RBK.View.Table import Table

class Tab(QWidget):
    def __init__(self):
        super().__init__()
        self.models = []
        grid = QGridLayout()
        self.list = List()
        grid.addWidget(self.list, 0, 0, -1, 8)
        self.table = Table()
        grid.addWidget(self.table, 0, 2, -1, -1)
        self.setLayout(grid)
        self.core = False

    def setModel(self, models):
        self.models = models
        self.models['db'].errored.connect(self.error)
        self.list.setModel(self.models['DataTypes'])
        self.list.dataTypeAdded.connect(self.models['db'].addDataType)
        self.list.dataTypeRemoved.connect(self.models['db'].removeDataType)
        self.table.fieldAdded.connect(self.models['db'].addField)
        self.table.fieldRemoved.connect(self.models['db'].removeField)
        self.list.resetTableView.connect(self.listItemSelected)

    def getWidget(self):
        return self

    def setCore(self, core):
        self.core = core
        self.list.setCore(core)

    @pyqtSlot(QModelIndex, int)
    def listItemSelected(self, new, mode):
        datatype = new.data()
        if mode==List.InputDataMode:
            listname = 'Data {0}'.format(datatype)
        else:    # List.EditDataTypeMode
            listname = 'Struct {0}'.format(datatype)
        self.table.setModel(self.models[listname])
        self.table.resizeColumnsToContents()

    @pyqtSlot(str)
    def error(self, message):
        qmb = QMessageBox.critical(self, 'Error!', 'Error: {0}.'.format(message))
        qmb.exec() 
